%% Z-scored trace + refined raster (fixed tick width)
clear; clc;

fname = 'Matlab.csv';
data  = readmatrix(fname);

%% Columns
x_black = data(:,1);
y_black_raw = data(:,2);

x_red   = data(:,3);
x_blue  = data(:,6);

%% ---- Z-score normalization of trace ----
mu  = mean(y_black_raw,'omitnan');
sigma = std(y_black_raw,'omitnan');

if sigma == 0 || isnan(sigma)
    error('Standard deviation is zero or NaN.');
end

y_black = (y_black_raw - mu) ./ sigma;

%% ---- Parameters ----
trace_lw      = 1.2;
blue_height   = 1.0;          % 藍色 tick 高度
red_height    = 1.25;         % 紅色比藍色高 25%
tick_width    = 1.5;          % 固定線寬（不再使用 duration）

%% ---- Auto baseline positioning ----
ymin_trace = min(y_black,[],'omitnan');
ymax_trace = max(y_black,[],'omitnan');
yrange     = ymax_trace - ymin_trace;

gap        = 0.3;   % Z-score unit gap
y_blue_base = ymin_trace - gap - blue_height;
y_red_base  = y_blue_base;   % 同一 baseline，只是高度不同

%% ---- Plot ----
fig = figure('Color','w'); hold on;

% Black trace
plot(x_black, y_black, 'k', 'LineWidth', trace_lw);

% Blue raster ticks (fixed width, vertical line)
for i = 1:numel(x_blue)
    if ~isnan(x_blue(i))
        plot([x_blue(i) x_blue(i)], ...
             [y_blue_base y_blue_base + blue_height], ...
             'Color',[0 114 178]/255, ...
             'LineWidth', tick_width);
    end
end

% Red onset ticks (25% taller)
for i = 1:numel(x_red)
    if ~isnan(x_red(i))
        plot([x_red(i) x_red(i)], ...
             [y_red_base y_red_base + red_height], ...
             'Color',[1 0 0], ...
             'LineWidth', tick_width);
    end
end

%% ---- Styling ----
box off
set(gca,'FontSize',12,'LineWidth',1,'TickDir','out');

xlabel('Time (sec)');
ylabel('Z-score of ΔF/F');

ylim([y_blue_base - 0.3, ymax_trace + 0.5]);

%% ---- Export ----
exportgraphics(fig, 'Trace_Zscore_Raster_Refined.pdf', 'ContentType','vector');
exportgraphics(fig, 'Trace_Zscore_Raster_Refined.png', 'Resolution', 600);
